<template>
    <view>
        <view class="flex face-row" :style="{height:sourceHeight+'px'}">
            <view class="flex-treble">
                <view style="margin-bottom: 5px">
                    <button class="cu-btn round bg-green" @click="useBaiDu">开始识别</button>
                </view>
                <!--<view>-->
                <!--<button class="cu-btn round lg bg-olive" @click="useFacePP">face++</button>-->
                <!--</view>-->
            </view>
            <view class="flex-treble">
                <block v-if="img_source.src && img_source.buf">
                    <image :src="img_source.src" class="face" @click="chooseImage_source"></image>
                </block>
                <block v-else>
                    <view class="uni-hello-addfile" @click="chooseImage_source">+ 选择BB图片</view>
                </block>
            </view>
            <view class="flex-treble">
                <view class="text-center">
                    <button class="cu-btn round bg-orange" @click="reset">重置</button>
                </view>
            </view>
        </view>
        <view class="grid face-row col-2" :style="{height:targetHeight+ 'px'}">
            <block v-for="(item,i) in img_target">
                <view class="tag">
                    <view class="tag-img">
                        <block v-if="item.src && img_source.buf">
                            <image :src="item.src" class="face"
                                   @click="chooseImage_target(i)"></image>
                        </block>
                        <block v-else>
                            <view class="uni-hello-addfile" @click="chooseImage_target(i)">+ 选择图片</view>
                        </block>
                    </view>
                    <view class="tag-like">{{item.like}}</view>
                </view>
            </block>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                title: 'Hello',
                sourceHeight: 0,
                targetHeight: 0,
                targetItemHeight: 0,
                img_source: {name: 'source', src: '', buf: ''},
                img_target: [
                    {
                        name: 'img_1',
                        src: '',
                        like: 0

                    },
                    {
                        name: 'img_2',
                        src: '',
                        like: 0

                    },
                    {
                        name: 'img_3',
                        src: '',
                        like: 0

                    },
                    {
                        name: 'img_4',
                        src: '',
                        like: 0

                    },
                    {
                        name: 'img_5',
                        src: '',
                        like: 0

                    },
                    {
                        name: 'img_6',
                        src: '',
                        like: 0

                    },
                ],

            }
        },
        onLoad() {
            this.sourceHeight = uni.getSystemInfoSync().windowWidth / 3;
            let winHeight = uni.getSystemInfoSync().windowHeight;
            this.targetHeight = winHeight - 50 - this.sourceHeight;
            this.targetItemHeight = this.targetHeight / 3;

            this.loadImgFromCache();
        },
        methods: {
            loadImgFromCache() {
                var sourceImg = this.PB.getStorage('source');
                if (sourceImg) {
                    this.img_source = sourceImg;
                }

                for (let i = 1; i <= 6; ++i) {
                    var targetImg = this.PB.getStorage('img_' + i);
                    if (targetImg) {
                        var indx = this.img_target.findIndex(q => q.name === targetImg.name);
                        if (indx >= 0) {
                            this.$set(this.img_target, indx, targetImg);
                        }
                    }
                }
            },
            reset() {
                this.img_source = {name: 'source', src: '', buf: ''};
                this.PB.removeStorage('source');
                this.img_target.forEach(q => {
                    q.src = '';
                    q.buf = '';
                    q.like = 0;
                    this.PB.removeStorage(q.name);
                })
            },
            chkImgSelect() {
                if (!this.img_source.buf) {
                    this.PB.toast('请先选择BB图片');
                    return false;
                }

                if (this.img_target.filter(q => q.buf && q.buf.length > 0).length === 0) {
                    this.PB.toast('请至少选择一张对比图片');
                    return false;
                }

                return true;
            },
            useBaiDu() {
                if (!this.chkImgSelect()) {
                    return;
                }

                uni.showLoading({
                    title: '请等待',
                    mask: true
                });
                setTimeout(() => {
                    uni.hideLoading();
                }, 5000);
                uni.request({
                    url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=UGBkTfzWFLGLeRmm0iiRtcMs&client_secret=ZMQTUQCgiFiUy1WNeT64ONDZTqBuiZft'
                }).then(data => {
                    let [error, res] = data;
                    if (error) {
                        this.PB.alert(error.errMsg);
                        return;
                    }

                    let baiduToken = res.data.access_token;

                    var i = 0;
                    for (var targetImg of this.img_target) {
                        // (function (p_sourceImg, p_targetImg, that) {
                        //     setTimeout(() => {
                        //         this.img_target.find(q => q.name == targetImg.name).like = a++;
                        //     });
                        // })(targetImg,"",this);

                        if (targetImg.buf) {
                            (function (p_sourceImg, p_targetImg, that) {
                                setTimeout(() => {
                                    let body = [{
                                        "image": p_sourceImg.buf, "image_type": "BASE64", "face_type": "LIVE",
                                        "quality_control": "LOW"
                                    },
                                        {
                                            "image": p_targetImg.buf,
                                            "image_type": "BASE64",
                                            "face_type": "LIVE",
                                            "quality_control": "LOW"
                                        }
                                    ];

                                    uni.request({
                                        url: 'https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=' + baiduToken,
                                        method: 'POST',
                                        data: body
                                    }).then(data => {
                                        let [error, res] = data;
                                        if (error) {
                                            that.PB.alert(error.errMsg);
                                            return;
                                        }
                                        let result = res.data;
                                        if (result.error_msg == 'SUCCESS') {
                                            console.log(p_targetImg.name + '相似度：' + result.result.score);
                                            // that.$nextTick(() => {
                                            let mTargetIMg = that.img_target.find(q => q.name == p_targetImg.name);
                                            if (mTargetIMg) {
                                                mTargetIMg.like = result.result.score;
                                                that.PB.setStorage(mTargetIMg.name, mTargetIMg);
                                            }

                                            // });
                                        } else {
                                            var msg = result.error_msg;
                                            if (msg.indexOf('limit') >= 0 || msg.indexOf('qbs') >= 0) {
                                                msg = '服务器繁忙，请稍后操作';
                                            }
                                            that.PB.toast(msg);
                                        }

                                    });
                                }, i * 800);
                            })(this.img_source, targetImg, this);
                            ++i;
                        }
                    }

                });
            },
            useFacePP() {
                if (!this.chkImgSelect()) {
                    return;
                }

                uni.showLoading({
                    title: '请等待',
                    mask: true
                });
                setTimeout(() => {
                    uni.hideLoading();
                }, 5000);
                var i = 0;
                for (var targetImg of this.img_target) {
                    if (targetImg.buf) {
                        (function (p_sourceImg, p_targetImg, that) {
                            setTimeout(() => {
                                var body = {
                                    "api_key": 'zcSpZCLn06HoU6vDDzxBZ8tlldnbISos',
                                    "api_secret": 'CExeOkkamqF589VPAQ8tnpEXVj174lh1',
                                    "image_base64_1": p_sourceImg.buf,
                                    "image_base64_2": p_targetImg.buf
                                };
                                uni.uploadFile({
                                    url: 'https://api-cn.faceplusplus.com/facepp/v3/compare',
                                    filePath: p_sourceImg.src,
                                    name: 'image_file',
                                    formData: body
                                }).then(data => {
                                    let [error, res] = data;
                                    if (error) {
                                        that.PB.alert(error.errMsg);
                                        console.log(error.errMsg);
                                        return;
                                    }
                                    let result = JSON.parse(res.data);
                                    if (result.error_message) {
                                        that.PB.toast(result.error_message);
                                        console.log(result.error_message);
                                    } else {
                                        let cc = result.confidence;
                                        if (!cc) {
                                            that.PB.toast('返回值不包含confidence');
                                            console.log('返回值不包含confidence');
                                        } else {
                                            let e4 = Number(result['thresholds']['1e-4']);
                                            let e5 = Number(result['thresholds']['1e-5']);
                                            // let like = cc >= e5 ? cc : -1;
                                            console.log(p_targetImg.name + '相似度：' + cc);

                                            let mTargetIMg = that.img_target.find(q => q.name === p_targetImg.name);
                                            if (mTargetIMg) {
                                                mTargetIMg.like = cc;

                                                that.PB.setStorage(mTargetIMg.name, mTargetIMg);
                                            }

                                        }

                                    }
                                });
                            }, i * 800);
                        })(this.img_source, targetImg, this);
                        ++i;
                    }
                }

            },
            getImgBase64(item, url) {
                console.log('开始getImgBase64');
                wx.getFileSystemManager().readFile({
                    filePath: url, //选择图片返回的相对路径
                    encoding: 'base64', //编码格式
                    success: res => { //成功的回调
                        console.log('getImgBase64完成');
                        // console.log('data:image/png;base64,' + res.data)
                        let base64 = res.data;
                        let maxLength = 1048576;
                        if (maxLength < base64.length) {
                            console.log('长度:' + base64.length);
                            let quality = Math.floor(100 * maxLength / base64.length);
                            console.log('压缩质量:' + quality);
                            // 如果超过微信限制的大小，则压缩
                            uni.compressImage({
                                src: url,
                                quality: quality,
                                success: res => {
                                    this.getImgBase64(item, res.tempFilePath)
                                },
                                fail: err => {
                                    console.log('压缩失败');
                                    this.PB.alert(err);
                                }
                            })
                        } else {
                            item.buf = base64;

                            // 把图片缓存到本地
                            this.PB.setStorage(item.name, item);
                        }
                    },
                    fail: res => {
                        this.PB.alert(res.errMsg);
                    }
                })
                // uni.request({
                //     url: url,
                //     responseType: 'arraybuffer'
                // }).then(data => {//data为一个数组，数组第一项为错误信息，第二项为返回数据
                //     console.log('getImgBase64完成');
                //     this.PB.alert(JSON.stringify(data));
                //     let [error, res] = data;
                //     if (error) {
                //         this.PB.alert(error.errMsg);
                //         return;
                //     }
                //     console.log('开始arrayBufferToBase64');
                //     let base64 = uni.arrayBufferToBase64(res.data);
                //
                //
                // }).catch(err => {
                //     console.log('catch请求getImgBase64失败:' + err);
                // });
            },
            chooseImage_source() {
                uni.chooseImage({
                    count: 1,
                    sizeType: ['compressed'],
                    // sourceType: ['album'],
                    success: (res) => {
                        console.log('chooseImage success, temp path is', res.tempFilePaths[0]);
                        this.img_source.src = res.tempFilePaths[0];
                        this.getImgBase64(this.img_source, this.img_source.src)
                    },
                    fail: (err) => {
                        console.log('chooseImage fail', err)
                    }
                })
            },
            chooseImage_target(imgIndex) {
                uni.chooseImage({
                    count: 1,
                    sizeType: ['compressed'],
                    // sourceType: ['album'],
                    success: (res) => {
                        console.log('chooseImage success, temp path is', res.tempFilePaths[0]);
                        this.img_target[imgIndex].src = res.tempFilePaths[0];
                        this.img_target[imgIndex].like = 0;
                        this.getImgBase64(this.img_target[imgIndex], this.img_target[imgIndex].src)
                    },
                    fail: (err) => {
                        console.log('chooseImage fail', err)
                    }
                })
            }
        }
    }
</script>

<style>
    .face-row {
        margin: 0 10px;
    }

    .face {
        width: 100%;
        height: 100%;
    }

    .uni-hello-addfile {
        text-align: center;
        background: #FFF;
        margin-top: 40px;
        color: #808080;
    }

    .tag {
        display: flex;
        flex-direction: column;
    }

    .tag-img {
        flex: 1;
    }

    .tag-like {
        text-align: center;
        height: 20px;
    }
</style>
